//
//  ForgetPwdViewController.swift
//  DriverSchoolAPP
//
//  Created by Logel on 2017/5/29.
//  Copyright © 2017年 Logel. All rights reserved.
//

import UIKit

class ForgetPwdViewController: UIViewController,LgCallBack{
    @IBOutlet weak var sendButton: UIButton!

    @IBOutlet weak var phoneLbl: UITextField!
    @IBOutlet weak var valideCodeLbl: UITextField!
    @IBOutlet weak var pwdLbl: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK-按钮倒计时
    
    var countdownTimer: Timer?
    
    var remainingSeconds: Int = 0 {
        willSet {
            sendButton.setTitle("\(newValue)秒", for: .normal)
            
            if newValue <= 0 {
                sendButton.setTitle("重新获取", for: .normal)
                isCounting = false
            }
        }
    }
    
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime(timer:)), userInfo: nil, repeats: true)
                
                remainingSeconds = 60
                
                sendButton.backgroundColor = UIColor.clear
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                
                sendButton.backgroundColor = UIColor.red
            }
            
            sendButton.isEnabled = !newValue
        }
    }
    
    func updateTime(timer: Timer) {
        // 计时开始时，逐秒减少remainingSeconds的值
        remainingSeconds -= 1
    }
    @IBAction func doGetCode(_ sender: UIButton) {
        if phoneLbl.text != "" {
            isCounting = true
            asyn_req_post(method: M_Validcode, cb: self, p: ["mobile":phoneLbl.text as AnyObject,"msgtype":"2" as AnyObject])
        }else{
            showMsg(msg: "请输入手机号")
        }
    }

    @IBAction func doReset(_ sender: UIButton) {
        if (phoneLbl.text != "" && valideCodeLbl.text != "" && pwdLbl.text != "") {
            asyn_req_post(method: M_Resetpw, cb: self, p: ["valideCode":valideCodeLbl.text as AnyObject,"userName":phoneLbl.text as AnyObject,"newPassWord":pwdLbl.text  as AnyObject])
        }else{
            showMsg(msg: "信息录入不完全！")
        }
    }
    
    func callBack(method: String, data: AnyObject) {
        let j = JSON(data)
        print(j)
        let head = parseMobileHead(x: j["MobileHead"])
        if head.code == "1" {
            if method == M_Resetpw {
                showMsg(msg: "重置密码成功")
            }
            
        }else{
            showMsg(msg: head.code)
        }
    }
}
